#!/usr/bin/with-contenv bashio
# /app/run.sh

# 获取配置
GITEE_REPO=$(bashio::config 'gitee_repo')
WWW_DIR="/homeassistant_config/www"
COMMUNITY_DIR="${WWW_DIR}/community"
STORAGE_DIR="/homeassistant_config/.storage"
RESOURCES_FILE="${STORAGE_DIR}/lovelace_resources"

# 创建必要的目录
mkdir -p "${WWW_DIR}" "${COMMUNITY_DIR}" "${STORAGE_DIR}"

# 转换 Gitee URL 为原始内容 URL
RAW_URL=$(echo "${GITEE_REPO}" | sed 's/gitee.com/gitee.com\/raw/')

# 下载并处理 JS 文件
bashio::log.info "从 ${GITEE_REPO} 下载资源..."

# 获取仓库文件列表
FILES=$(curl -s "${RAW_URL}/master" | grep -o '"name":"[^"]*\.js"' | cut -d'"' -f4)

# 初始化或读取现有的 resources 文件
if [ -f "${RESOURCES_FILE}" ]; then
    EXISTING_URLS=$(jq -r '.data.items[].url' "${RESOURCES_FILE}")
else
    echo '{"version":1,"minor_version":1,"key":"lovelace_resources","data":{"items":[]}}' > "${RESOURCES_FILE}"
    EXISTING_URLS=""
fi

# 下载文件并更新配置
for FILE in ${FILES}; do
    FILE_URL="${RAW_URL}/master/${FILE}"
    LOCAL_PATH="${COMMUNITY_DIR}/${FILE}"
    RESOURCE_URL="/local/community/${FILE}"
    
    # 检查是否已存在
    if echo "${EXISTING_URLS}" | grep -q "^${RESOURCE_URL}$"; then
        bashio::log.info "${FILE} 资源已存在,跳过..."
        continue
    fi
    
    # 下载文件
    if curl -s "${FILE_URL}" -o "${LOCAL_PATH}"; then
        bashio::log.info "下载成功: ${FILE}"
        
        # 生成唯一ID
        RESOURCE_ID=$(cat /proc/sys/kernel/random/uuid | sed 's/-//g')
        
        # 添加到 resources 配置
        TMP_FILE=$(mktemp)
        jq --arg id "${RESOURCE_ID}" \
           --arg url "${RESOURCE_URL}" \
           '.data.items += [{"id": $id, "url": $url, "type": "module"}]' \
           "${RESOURCES_FILE}" > "${TMP_FILE}"
        mv "${TMP_FILE}" "${RESOURCES_FILE}"
        
        bashio::log.info "添加资源: ${RESOURCE_URL}"
    else
        bashio::log.error "下载失败: ${FILE}"
    fi
done

bashio::log.info "处理完成"
